package com.yz;

import com.yz.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author yuanzheng
 * @date 2020/7/7-11:56
 */
public class TestPost {
    @Autowired
    private RestTemplate restTemplate;
    private String uri = "";

    @PostMapping()
    public User getUser1() {
        // 1-postForObject()
        User user = new User("A", 20);
        User user1 = restTemplate.postForObject(uri, user, User.class);
        return user1;
    }

    @PostMapping()
    public ResponseEntity<User> getUser2() {
        // 2-postForEntity()
        User user = new User("A", 20);
        ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class);
        return responseEntity1;
    }

    @PostMapping()
    public ResponseEntity<User> getUser3() throws URISyntaxException {
        // 3-exchange()
        User user = new User("A", 20);
        RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
        ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
        return responseEntity2;
    }

    @PostMapping()
    public String getUser4() {
        String url = "http://demo/api/book/";
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String requestJson = "{...}";
        HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        System.out.println(result);
        return result;
    }

    @PostMapping()
    public ResponseEntity<String> getUser5() throws URISyntaxException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://47.xxx.xxx.96/register/checkEmail";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("email", "844072586@qq.com");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        System.out.println(response.getBody());
        return response;
    }


}
